/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.server.modules.sys.service.customer.export;

import com.server.common.persistence.Page;
import com.server.common.service.CrudService;
import com.server.common.utils.StringUtils;
import com.server.modules.sys.common.StaticDefine;
import com.server.modules.sys.dao.customer.export.CustomerExportLogDao;
import com.server.modules.sys.entity.customer.export.CustomerExportLog;
import com.server.modules.sys.entity.customer.impt.CustomerImport;
import com.server.modules.sys.utils.CollectionGroupUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static org.apache.batik.svggen.font.table.Table.name;
import static org.nutz.aop.AbstractClassAgent.t;

/**
 * 客户导出日志Service
 * @author 丁光彪
 * @version 2016-11-08
 */
@Service
@Transactional(readOnly = true)
public class CustomerExportLogService extends CrudService<CustomerExportLogDao, CustomerExportLog> {
    @Resource
    private  SqlSessionFactoryBean sqlSessionFactoryBean;
	public CustomerExportLog get(String id) {
		return super.get(id);
	}
	
	public List<CustomerExportLog> findList(CustomerExportLog customerExportLog) {
		return super.findList(customerExportLog);
	}
	
	public Page<CustomerExportLog> findPage(Page<CustomerExportLog> page, CustomerExportLog customerExportLog) {
		return super.findPage(page, customerExportLog);
	}
    public List<HSSFWorkbook> data2excel(List<CustomerImport> list,Integer everyNum){
        List<List<CustomerImport>> lists = CollectionGroupUtils.groupListByQuantity(list, everyNum);
        List<HSSFWorkbook> wbs=new ArrayList<>();
        for (List<CustomerImport> customerImports : lists) {
            //创建HSSFWorkbook对象(excel的文档对象)
            HSSFWorkbook wb = new HSSFWorkbook();

            //建立新的sheet对象（excel的表单）
            HSSFSheet sheetCar = wb.createSheet("车辆客户信息");
            HSSFRow sheetCarRow0 = sheetCar.createRow(0);
            sheetCarRow0.createCell(0).setCellValue("姓名");
            sheetCarRow0.createCell(1).setCellValue("手机");
            sheetCarRow0.createCell(2).setCellValue("座机");
            sheetCarRow0.createCell(3).setCellValue("车辆信息");
            sheetCarRow0.createCell(4).setCellValue("车牌");
            sheetCarRow0.createCell(5).setCellValue("上牌时间");
            HSSFSheet sheetHouse = wb.createSheet("房产客户信息");
            HSSFRow sheetHouseRow0 = sheetHouse.createRow(0);
            sheetHouseRow0.createCell(0).setCellValue("姓名");
            sheetHouseRow0.createCell(1).setCellValue("手机");
            sheetHouseRow0.createCell(2).setCellValue("座机");
            sheetHouseRow0.createCell(3).setCellValue("房产信息");
            sheetHouseRow0.createCell(4).setCellValue("户型");
            sheetHouseRow0.createCell(5).setCellValue("地址");
            HSSFSheet sheetOther = wb.createSheet("资料不全客户信息");
            HSSFRow sheetOtherRow0 = sheetOther.createRow(0);
            sheetOtherRow0.createCell(0).setCellValue("姓名");
            sheetOtherRow0.createCell(1).setCellValue("手机");
            sheetOtherRow0.createCell(2).setCellValue("座机");
            sheetOtherRow0.createCell(3).setCellValue("公司名称");
            sheetOtherRow0.createCell(4).setCellValue("职务");
            sheetOtherRow0.createCell(5).setCellValue("地址");
            sheetCar.setColumnWidth(1, 10 * 512);
            sheetCar.setColumnWidth(2, 10 * 512);
            sheetCar.setColumnWidth(3, 10 * 512);
            sheetCar.setColumnWidth(4, 10 * 512);
            sheetCar.setColumnWidth(5, 10 * 512);
            sheetCar.setColumnWidth(6, 10 * 512);

            sheetHouse.setColumnWidth(1, 10 * 512);
            sheetHouse.setColumnWidth(2, 10 * 512);
            sheetHouse.setColumnWidth(3, 10 * 512);
            sheetHouse.setColumnWidth(4, 10 * 512);
            sheetHouse.setColumnWidth(5, 10 * 512);
            sheetHouse.setColumnWidth(6, 10 * 512);

            sheetOther.setColumnWidth(1, 10 * 512);
            sheetOther.setColumnWidth(2, 10 * 512);
            sheetOther.setColumnWidth(3, 10 * 512);
            sheetOther.setColumnWidth(4, 10 * 512);
            sheetOther.setColumnWidth(5, 10 * 512);
            sheetOther.setColumnWidth(6, 10 * 512);
            for (CustomerImport customerImport : customerImports) {
                String type = customerImport.getType();
                String name = customerImport.getName();
                String mobile = customerImport.getMobile();
                String tel = customerImport.getTel();
                String addr = customerImport.getAddr();

                if(StaticDefine.CUSTOMER_IMPORT_TYPE.car.equals(type)){
                    int lastRowNum = sheetCar.getLastRowNum()+1;
                    HSSFRow row = sheetCar.createRow(lastRowNum);
                    String carInfo = customerImport.getCarInfo();
                    String plateno = customerImport.getPlateno();
                    String platenoRegTime = customerImport.getPlatenoRegTime();
                    row.createCell(0).setCellValue(StringUtils.isBlank(name)?"":name);
                    row.createCell(1).setCellValue(StringUtils.isBlank(mobile)?"":mobile);
                    row.createCell(2).setCellValue(StringUtils.isBlank(tel)?"":tel);
                    row.createCell(3).setCellValue(StringUtils.isBlank(carInfo)?"":carInfo);
                    row.createCell(4).setCellValue(StringUtils.isBlank(plateno)?"":plateno);
                    row.createCell(5).setCellValue(StringUtils.isBlank(platenoRegTime)?"":platenoRegTime);
                }else if(StaticDefine.CUSTOMER_IMPORT_TYPE.house.equals(type)){
                    int lastRowNum = sheetHouse.getLastRowNum()+1;
                    HSSFRow row = sheetHouse.createRow(lastRowNum);
                    String housePropertyInfo = customerImport.getHousePropertyInfo();
                    String household = customerImport.getHousehold();
                    row.createCell(0).setCellValue(StringUtils.isBlank(name)?"":name);
                    row.createCell(1).setCellValue(StringUtils.isBlank(mobile)?"":mobile);
                    row.createCell(2).setCellValue(StringUtils.isBlank(tel)?"":tel);
                    row.createCell(3).setCellValue(StringUtils.isBlank(housePropertyInfo)?"":housePropertyInfo);
                    row.createCell(4).setCellValue(StringUtils.isBlank(household)?"":household);
                    row.createCell(5).setCellValue(StringUtils.isBlank(addr)?"":addr);
                }else if(StaticDefine.CUSTOMER_IMPORT_TYPE.other.equals(type)){
                    int lastRowNum = sheetOther.getLastRowNum()+1;
                    HSSFRow row = sheetOther.createRow(lastRowNum);
                    String company = customerImport.getCompany();
                    String post = customerImport.getPost();
                    row.createCell(0).setCellValue(StringUtils.isBlank(name)?"":name);
                    row.createCell(1).setCellValue(StringUtils.isBlank(mobile)?"":mobile);
                    row.createCell(2).setCellValue(StringUtils.isBlank(tel)?"":tel);
                    row.createCell(3).setCellValue(StringUtils.isBlank(company)?"":company);
                    row.createCell(4).setCellValue(StringUtils.isBlank(post)?"":post);
                    row.createCell(5).setCellValue(StringUtils.isBlank(addr)?"":addr);
                }
            }
            //删除没有数据的sheet
            int i=0;
            List<String> removeSheet=new ArrayList<>();

            for (Sheet sheet : wb) {
                int lastRowNum = sheet.getLastRowNum();
                if(lastRowNum<1){
                    removeSheet.add(sheet.getSheetName());
                }
                i++;
            }
            for (String sheetName : removeSheet) {
                wb.removeSheetAt(wb.getSheetIndex(sheetName));
            }
            wbs.add(wb);
        }
        list=new ArrayList<>();
        for (List<CustomerImport> customerImports : lists) {
            list.addAll(customerImports);
        }
        return wbs;
    }
	@Transactional(readOnly = false)
	public void save(CustomerExportLog customerExportLog) {
		super.save(customerExportLog);
	}
	
	@Transactional(readOnly = false)
	public void delete(CustomerExportLog customerExportLog) {
		super.delete(customerExportLog);
	}
    @Transactional(readOnly = false)
	public int batchInsert(List<CustomerExportLog> list) {
		int successNum=0;
        long begin=System.currentTimeMillis();
        SqlSession session =null;
        int commitCountEveryTime=10000;
                 try {
                     SqlSessionFactory sqlSessionFactory1 = sqlSessionFactoryBean.getObject();
                     session = sqlSessionFactory1.openSession(ExecutorType.BATCH, false);
                     String statement = "com.server.modules.sys.dao.customer.export.CustomerExportLogDao.insertBatch";//映射sql的标识字符串
                         int commitCount = (int) Math.ceil(list.size() / (double) commitCountEveryTime);
                         List<CustomerExportLog> tempList = new ArrayList<CustomerExportLog>(commitCountEveryTime);
                         int start, stop;
                         Long startTime = System.currentTimeMillis();
                         for (int i = 0; i < commitCount; i++) {
                                 tempList.clear();
                                 start = i * commitCountEveryTime;
                                 stop = Math.min(i * commitCountEveryTime + commitCountEveryTime - 1, list.size() - 1);
                                 for (int j = start; j <= stop; j++) {
                                	 CustomerExportLog ci = list.get(j);
                                     tempList.add(ci);
                                  }
                                 int j=session.insert(statement, tempList);
                                  successNum+= tempList.size();
                                 session.commit();
                                 session.clearCache();
                             }
                         Long endTime = System.currentTimeMillis();
                         //logger.debug("batchCommit耗时：" + (endTime - startTime) + "毫秒");
                     } catch (Exception e) {
                        // logger.error("batchCommit error!", e);
                         e.printStackTrace();
                         session.rollback();
                     } finally {
                         if (session != null) {
                                 session.close();
                             }
                     }
        // 结束时间  
        Long end = new Date().getTime();  
        // 耗时  
        System.out.println("插入数据条数 : " + successNum);
        System.out.println("cast : " + (end - begin) / 1000 + " s"); 
        return successNum;
	}
	
}